package org.liaohailong.library.widget.common;

import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import org.liaohailong.library.R;

/**
 * Author: liaohailong
 * Date: 2022/8/27
 * Time: 11:51
 * desc: TextView 功能扩展
 * 1，支持圆角，部分圆角
 * 2，支持点击按压反馈。
 **/
public class CommonTextView extends androidx.appcompat.widget.AppCompatTextView {

    private final CommonCropDelegate cropDelegate;


    public CommonTextView(@NonNull Context context) {
        this(context, null);
    }

    public CommonTextView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CommonTextView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CommonTextView);

        // 圆角半径
        int radius = a.getDimensionPixelSize(R.styleable.CommonTextView_radius, 0);

        // 边线属性
        float strokeWidth = a.getDimensionPixelSize(R.styleable.CommonFrameLayout_stroke_width, 0);
        int strokeColor = a.getColor(R.styleable.CommonFrameLayout_stroke_color, Color.TRANSPARENT);


        a.recycle();

        cropDelegate = new CommonCropDelegate(this);
        cropDelegate.setup(radius, strokeWidth, strokeColor);
    }

    @Override
    public void setBackgroundDrawable(Drawable background) {
        background = CommonClickDelegate.getBackgroundDrawable(background);
        super.setBackgroundDrawable(background);
    }

    @Override
    public void setTextColor(int color) {
        ColorStateList colorStateList = CommonClickDelegate.getColorStateList(color, 0.5f);
        super.setTextColor(colorStateList);
    }

    @Override
    public void setTextColor(ColorStateList colors) {
        if (colors.isStateful()) {
            super.setTextColor(colors);
        } else {
            int color = colors.getDefaultColor();
            ColorStateList colorStateList = CommonClickDelegate.getColorStateList(color, 0.5f);
            super.setTextColor(colorStateList);
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        cropDelegate.prepareShape(w, h);
    }

    public void setRadius(int radius) {
        cropDelegate.setRadius(radius);
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);
        // 绘制边线
        cropDelegate.drawStroke(canvas);
    }
}
